#include "stdafx.h"
#include "GameTimer.h"


//CTOR & DTOR
GameTimer::GameTimer()
{
	#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
	QueryPerformanceFrequency(&frequency);
	startCount.QuadPart = 0;
	endCount.QuadPart = 0;
	#else
	startCount.tv_sec = startCount.tv_usec = 0;
	endCount.tv_sec = endCount.tv_usec = 0;
	#endif

	_stopped = 0;
	_startTimeInMicroSec = 0;
	_endTimeInMicroSec = 0;
}

GameTimer::~GameTimer()
{
}


//METHODS
void GameTimer::start()
{
	_stopped = 0; // reset stop flag
	#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
	QueryPerformanceCounter(&startCount);
	#else
	gettimeofday(&startCount, NULL);
	#endif
}

void GameTimer::stop()
{
	_stopped = 1; // set GameTimer stopped flag

	#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
	QueryPerformanceCounter(&endCount);
	#else
	gettimeofday(&endCount, NULL);
	#endif
}


//GETTER
double GameTimer::getElapsedTimeInMicroSec()
{
	#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
	if(!_stopped)
		QueryPerformanceCounter(&endCount);

	_startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart);
	_endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart);
	#else
	if(!stopped)
		gettimeofday(&endCount, NULL);

	startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec;
	endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec;
	#endif

	return _endTimeInMicroSec - _startTimeInMicroSec;
}

double GameTimer::getStartTimeInMilliSec()
{
	#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
	return (startCount.QuadPart * (1000000.0 / frequency.QuadPart)) * 0.000001;
	#else
	return ((startCount.tv_sec * 1000000.0) + startCount.tv_usec) * 0.001;
	#endif
}

double GameTimer::getElapsedTimeInMilliSec()
{
	return this->getElapsedTimeInMicroSec() * 0.001;
}

double GameTimer::getElapsedTimeInSec()
{
	return this->getElapsedTimeInMicroSec() * 0.000001;
}

double GameTimer::getElapsedTime()
{
	return this->getElapsedTimeInSec();
}